package cc.smarnet.caihou.phone.warehouse;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.List;

import cc.smarnet.caihou.IPConfig;

import cc.smarnet.caihou.R;
import cc.smarnet.caihou.adapter.WarehouseAdapter;
import cc.smarnet.caihou.adapter.SpacesItemDecoration;
import cc.smarnet.caihou.entity.Warehouse;
import cc.smarnet.caihou.phone.MainPageActivity;
import cc.smarnet.caihou.phone.bracts.BractsActivity;
import okhttp3.Call;

/**
* 入库信息的activity
* */
public class WarehouseActivity extends AppCompatActivity {
    private RefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private LinearLayout failLoadLinearLayout;
    private LinearLayout noDataLinearLayout;
    private ProgressBar progressBar;
    private ImageButton imageButton;
    private Button addButton;

    private String token;

    private int pageNo = 1;// 取数分页的开始页
    private int pageSize = 4;// 每次取数的数量

    List<Warehouse> warehouseList = new ArrayList<>();
    WarehouseAdapter warehouseAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_warehouse);

        getSupportActionBar().hide();//隐藏标题栏

        initViews();
        noDataLinearLayout.setVisibility(View.GONE);// 隐藏暂无数据的信息
        failLoadLinearLayout.setVisibility(View.GONE);// 隐藏数据加载失败的信息

        getToken();
        getWarehouseInfo();
        // 点击返回按钮的监听
        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(WarehouseActivity.this, MainPageActivity.class);
                startActivity(intent);
            }
        });
        // 点击新增按钮的监听
        addButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(WarehouseActivity.this, WarehouseAddActivity.class);
                startActivity(intent);
            }
        });
        //设置layoutManager,可以设置显示效果，是线性布局、grid布局，还是瀑布流布局(参数是：上下文、列表方向（横向还是纵向）、是否倒叙)
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        recyclerView.addItemDecoration(new SpacesItemDecoration(20));// 设置item的上下左右边距
        recyclerView.setHasFixedSize(true);
        // 这里使用适配器的目的在于使系统不再报‘E/RecyclerView: No adapter attached; skipping layout’的错误
        /*List<warehouse> nullList=new ArrayList<>();
        warehouseAdapter=new warehouseAdapter(nullList);
        recyclerView.setAdapter(warehouseAdapter);*/

        // 下拉刷新，目前在此就不做业务处理了，因为初始时加载的那几条数据就是从第一条开始的查询的
        refreshLayout.setOnRefreshListener(new OnRefreshListener() { //下拉刷新
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refreshlayout.finishRefresh();
            }
        });

        //上拉加载更多
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(final RefreshLayout refreshlayout) {
                getWarehouseInfo();
                refreshlayout.finishLoadMore(0);
            }
        });
    }

    public void initViews() {
        refreshLayout = findViewById(R.id.warehouse_refreshLayout);
        recyclerView = findViewById(R.id.warehouse_recyclerView);
        failLoadLinearLayout = findViewById(R.id.warehouse_failLoad_linearLayout);
        noDataLinearLayout = findViewById(R.id.warehouse_noData_linearLayout);
        progressBar = findViewById(R.id.warehouse_progressBar);
        imageButton = findViewById(R.id.warehouse_return);
        addButton = findViewById(R.id.warehouse_add_button);
    }

    public void getToken() {
        SharedPreferences sp = getSharedPreferences("userInfo", MODE_PRIVATE);
        token = sp.getString("token", null);
    }

    public void getWarehouseInfo() {
        progressBar.setVisibility(View.VISIBLE);
        String url = IPConfig.baseUrl + "/flower/flowerTagIn/list";
        OkHttpUtils
                .get()
                .addHeader("X-Access-Token", token)
                .addParams("pageNo", String.valueOf(pageNo))
                .addParams("pageSize", String.valueOf(pageSize))
                .url(url)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        progressBar.setVisibility(View.GONE);// 设置加载效果不可见
                        failLoadLinearLayout.setVisibility(View.VISIBLE);// 显示数据加载失败的信息
                    }

                    @Override
                    public void onResponse(String response, int ID) {
                        progressBar.setVisibility(View.GONE);// 设置加载效果不可见
                        failLoadLinearLayout.setVisibility(View.GONE);// 隐藏数据加载失败的信息
                        progressBar.setVisibility(View.GONE);// 设置加载效果不可见
                        boolean success = Boolean.parseBoolean(JSON.parseObject(response).getString("success"));
                        if (success) {
                            String result = JSON.parseObject(response).getString("result");
                            String records = JSON.parseObject(result).getString("records");
                            JSONArray jsonArray = JSON.parseArray(records);
                            // 获取入库信息并存到warehouseList中
                            for (int i = 0; i < jsonArray.size(); i++) {
                                String id = "";
                                String createTime=""; // 创建日期
                                String createUser=""; // 创建人
                                String flowerPoleLength=""; // 花杆长度
                                String packingSpecifications=""; // 打包规格
                                String sortTime=""; // 分拣日期
                                String baseName=""; // 来源基地
                                String greenhouseName=""; // 来源大棚
                                Integer tagNum=0; // 入库数量
                                String variety=""; // 采收品种
                                String varietyCode=""; // 品种编码
                                String classes=""; // 花卉等级

                                JSONObject jsonObj = jsonArray.getJSONObject(i);
                                if (jsonObj.containsKey("id")) {
                                    id = jsonObj.getString("id");
                                }
                                if (jsonObj.containsKey("createTime")) {
                                    createTime = jsonObj.getString("createTime");
                                }
                                if (jsonObj.containsKey("createUser")) {
                                    createUser = jsonObj.getString("createUser");
                                }
                                if (jsonObj.containsKey("flowerPoleLength")) {
                                    flowerPoleLength = jsonObj.getString("flowerPoleLength");
                                }
                                if (jsonObj.containsKey("packingSpecifications")) {
                                    packingSpecifications = jsonObj.getString("packingSpecifications");
                                }
                                if (jsonObj.containsKey("sortTime")) {
                                    sortTime = jsonObj.getString("sortTime");
                                }
                                if (jsonObj.containsKey("baseName")) {
                                    baseName = jsonObj.getString("baseName");
                                }
                                if (jsonObj.containsKey("greenhouseName")) {
                                    greenhouseName = jsonObj.getString("greenhouseName");
                                }
                                if (jsonObj.containsKey("tagNum")) {
                                    tagNum = jsonObj.getInteger("tagNum");
                                }
                                if (jsonObj.containsKey("variety")) {
                                    variety = jsonObj.getString("variety");
                                }
                                if (jsonObj.containsKey("varietyCode")) {
                                    varietyCode = jsonObj.getString("varietyCode");
                                }
                                if (jsonObj.containsKey("classes")) {
                                    classes = jsonObj.getString("classes");
                                }

                                Warehouse warehouse = new Warehouse();
                                warehouse.setId(id);
                                warehouse.setCreateTime(createTime);
                                warehouse.setCreateUser(createUser);
                                warehouse.setFlowerPoleLength(flowerPoleLength);
                                warehouse.setPackingSpecifications(packingSpecifications);
                                warehouse.setSortTime(sortTime);
                                warehouse.setBaseName(baseName);
                                warehouse.setGreenhouseName(greenhouseName);
                                warehouse.setTagNum(tagNum);
                                warehouse.setVariety(variety);
                                warehouse.setVarietyCode(varietyCode);
                                warehouse.setClasses(classes);

                                warehouseList.add(warehouse);
                            }
                            if (warehouseList.size() > 0) {// 如果warehouseList中有数据的话就通过warehouseAdapter将数据显示在界面上
                                warehouseAdapter = new WarehouseAdapter(getApplicationContext(),warehouseList);
                                recyclerView.setAdapter(warehouseAdapter);
                            }else {// 否则让暂无数据的信息显示在界面上
                                noDataLinearLayout.setVisibility(View.VISIBLE);
                            }

                            int total=Integer.valueOf(JSON.parseObject(result).getString("total"));//数据在数据库中的总数
                            int current=Integer.valueOf(JSON.parseObject(result).getString("current"));//该次取数是第几次
                            if (current*pageSize>=total){
                                Toast.makeText(WarehouseActivity.this, "已加载完所有数据", Toast.LENGTH_SHORT).show();
                            }

                            pageNo += 1;
                        }
                    }
                });
    }
}